package com.atguigu.spzx.product.service.Impl;

import com.atguigu.spyx.model.vo.h5.CategoryVo;
import com.atguigu.spzx.product.mapper.CategoryMapper;
import com.atguigu.spzx.product.service.CategoryService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LT
 * @create 2023-11-17-18:37
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Resource
    CategoryMapper categoryMapper;

    @Cacheable(value = "product:cates",key = "'all'")
    @Override
    public List<CategoryVo> findCategoryTree() {
        List<CategoryVo> categoryVoList = categoryMapper.findAll();
        List<CategoryVo> parents = categoryVoList.stream()
                .filter(categoryVo -> categoryVo.getParentId().equals(0l))
                .collect(Collectors.toList());
                buildCategoryTree(parents,categoryVoList);
        return parents;
    }

    private void buildCategoryTree(List<CategoryVo> parents, List<CategoryVo> all) {

        if (CollectionUtils.isEmpty(parents)){
            return;
        }
        parents.forEach(parent->{
            List<CategoryVo> children = all.stream().filter(categoryVo ->
                categoryVo.getParentId().equals(parent.getId()))
                .collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(children)){
                parent.setChildren(children);
            }
            buildCategoryTree(children,all);

        });
    }
}
